/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yucc.girlimages.ui;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;

import com.actionbarsherlock.R.style;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.umeng.analytics.MobclickAgent;
import com.umeng.api.sns.UMSNSException;
import com.umeng.api.sns.UMSnsService;
import com.umeng.api.sns.UMSnsService.DataSendCallbackListener;
import com.umeng.api.sns.UMSnsService.RETURN_STATUS;
import com.yucc.girlimages.Config;
import com.yucc.girlimages.GirlsApplication;
import com.yucc.girlimages.R;
import com.yucc.girlimages.ad.AdPlatform;
import com.yucc.girlimages.ad.AdPlatform.GetPointFailureCallBack;
import com.yucc.girlimages.ad.AdPlatform.GetPointSuccessCallBack;
import com.yucc.girlimages.ad.AdPlatformClient;
import com.yucc.girlimages.io.Db4oHelper;
import com.yucc.girlimages.io.upyun.ExtImageWorkerAdapter;
import com.yucc.girlimages.io.upyun.FolderItem;
import com.yucc.girlimages.ui.widget.TouchImageView.TouchEventListener;
import com.yucc.girlimages.util.Logger;
import com.yucc.girlimages.util.cache.ImageCache;
import com.yucc.girlimages.util.cache.ImageFetcher;
import com.yucc.girlimages.util.cache.ImageResizer;
import com.yucc.girlimages.util.cache.ImageWorker;
import com.yucc.girlimages.util.cache.Utils;

public class DetailActivity extends SherlockFragmentActivity implements
		OnClickListener{
	private static final String TAG = "DetailActivity";
	private static final String IMAGE_CACHE_DIR = "images";
	public static final String EXTRA_IMAGE_POSITION = "extra_image_position";
	public static final String EXTRA_ADAPTER = "extra_adapter";
	public static final String EXTRA_CATEGORY = "extra_category";

	ImagePagerAdapter mAdapter;
	private ImageResizer mImageWorker;
	EnableDisableViewPager mPager;
	private ExtImageWorkerAdapter mExtImageWorkerAdapter;
	AutoPlay mAutoPlay;
	MyMainHandler mMainHandler;
	private MyAsyncHandler mAsyncHandler;
	private byte[] mCurrentImageBytes;
	private boolean isImageByteInited;
	private HandlerThread mAsyncthread ;
	private Db4oHelper mDb4oHelper ;
	private int mCurrentPoint ;
	private boolean isUnlocked ;
	private int mUnlockTime ;
	private int mUnlockBase ;
	private String mCategory ; 
	
	//hold Objects
	private AdPlatform updater;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(style.Theme_Sherlock_NoActionBar);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_detail_pager);

		// Fetch screen height and width, to use as our max size when loading
		// images as this
		// activity runs full screen
		final DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		final int height = displaymetrics.heightPixels;
		final int width = displaymetrics.widthPixels;
		final int longest = height > width ? height : width;

		mMainHandler = new MyMainHandler(this);
		
		mDb4oHelper = new Db4oHelper(this) ;
		
		isUnlocked = getSharedPreferences(Config.SHAF_NAME, MODE_PRIVATE).getBoolean(Config.SHAF_UNLOCKED, false) ;
		if(!isUnlocked) {
			MobclickAgent.updateOnlineConfig(this);
			updater = AdPlatformClient.getAdPlatform(this, AdPlatformClient.WAPS) ;
			
			updater.setFailureCallBack(failureCallBack) ;
			updater.setSuccessCallBack(successCallBack) ;
			String temp = MobclickAgent.getConfigParams(this, Config.PARAM_UNLOCK_TIME) ;
			Logger.d(TAG, "online param mUnlockTime ="+temp+".") ;
			mUnlockTime = "".equals(temp) ? 1 :Integer.valueOf(temp) ;
			temp = MobclickAgent.getConfigParams(this, Config.PARAM_UNLOCK_BASE) ;
			Logger.d(TAG, "online param mUnlockBase="+temp+".") ;
			mUnlockBase = "".equals(temp) ? 35 :Integer.valueOf(temp) ;
		}

		mExtImageWorkerAdapter = getIntent().getParcelableExtra(EXTRA_ADAPTER);
		mCategory = getIntent().getStringExtra(EXTRA_CATEGORY) ;
		mExtImageWorkerAdapter.setThumb(false);

		// The ImageWorker takes care of loading images into our ImageView
		// children asynchronously
		mImageWorker = new ImageFetcher(this, longest);
		mImageWorker.setAdapter(mExtImageWorkerAdapter);
		mImageWorker.setImageCache(ImageCache.findOrCreateCache(this,
				IMAGE_CACHE_DIR));
		mImageWorker.setImageFadeIn(false);

		// Set up ViewPager and backing adapter
		mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
				mImageWorker.getAdapter().getSize());
		mPager = (EnableDisableViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);
		mPager.setPageMargin((int) getResources().getDimension(
				R.dimen.image_detail_pager_margin));

		// Set up activity to go full screen
		getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
		
		// Enable some additional newer visibility and ActionBar features to
		// create a more immersive
		// photo viewing experience
		// final ActionBar actionBar = getSupportActionBar();
		// if (Utils.hasActionBar()) {
		//
		// // Enable "up" navigation on ActionBar icon and hide title text
		// actionBar.setDisplayHomeAsUpEnabled(false);
		// actionBar.setDisplayShowTitleEnabled(false);
		//
		// // Start low profile mode and hide ActionBar
		// mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
		// actionBar.hide();
		//
		// // Hide and show the ActionBar as the visibility changes
		// mPager.setOnSystemUiVisibilityChangeListener(
		// new View.OnSystemUiVisibilityChangeListener() {
		// @Override
		// public void onSystemUiVisibilityChange(int vis) {
		// if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
		// actionBar.hide();
		// } else {
		// actionBar.show();
		// }
		// }
		// });
		// }else{
		// actionBar.setDisplayHomeAsUpEnabled(false);
		// actionBar.setDisplayShowTitleEnabled(false);
		// actionBar.hide() ;
		//
		// //确保高低版本的体验一致
		// mPager.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// if(event.getAction() == MotionEvent.ACTION_UP){
		// if(actionBar.isShowing()){
		// actionBar.hide() ;
		// }else{
		// actionBar.show() ;
		// }
		// return true;
		// }
		// return false ;
		// }
		//
		// }) ;
		// }

		// Set the current item based on the extra passed in to this activity
		final int extraCurrentItem = getIntent().getIntExtra(
				EXTRA_IMAGE_POSITION, -1);
		if (extraCurrentItem != -1) {
			mPager.setCurrentItem(extraCurrentItem);
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(!isUnlocked) 
			updater.getPoints(this) ;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// Home or "up" navigation
			final Intent intent = new Intent(this, CategoryThumbsActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.menu_auto_play:
			if (mAutoPlay == null) {
				mAutoPlay = new AutoPlay(mMainHandler);
				mAutoPlay.start() ;
			}
			mAutoPlay.startOrStopPlay() ;
			return true;
		case R.id.menu_save:
			//统计保存信息
			MobclickAgent.onEvent(this,"save_to_sdcard",mCategory);
			if(isUnlocked || mCurrentPoint >= mUnlockTime*50){
				getAsyncHandler().sendEmptyMessage(MyAsyncHandler.WHAT_SAVE_FILE);
			}else if(mCurrentPoint > 0){
				showDialog(String.format(getResources().getString(R.string.point_text),mCurrentPoint,mUnlockTime*mUnlockBase));
			}else{
				showDialog(String.format(getResources().getString(R.string.point_first_alert),mUnlockTime,mUnlockTime*mUnlockBase)) ;
			}
			return true;
		case R.id.menu_set_as_wallpaper:
			MobclickAgent.onEvent(this,"set_as_wallpaper",mCategory);
			Message msg = getAsyncHandler().obtainMessage(
					MyAsyncHandler.WHAT_SET_WALLPAPER);
			msg.obj = getCurrentBitmap();
			getAsyncHandler().sendMessage(msg);
			return true;
		case R.id.menu_share:
			shareImage();
			return true;
		case R.id.menu_fav:
			MobclickAgent.onEvent(this,"fav",mCategory);
			getAsyncHandler().sendEmptyMessage(MyAsyncHandler.WHAT_SAVE_FAV_ITEM) ;
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void showDialog(String title) {
        DialogFragment newFragment = MyAlertDialogFragment.newInstance(title
                );
        newFragment.show(getSupportFragmentManager(), "dialog");
    }
	
	private void saveToFav(){
		final FolderItem item = mExtImageWorkerAdapter.getList().get(mPager.getCurrentItem() ) ;
		item.haveFaved = true ;
		mDb4oHelper.saveFavFolderItem(item) ;
		mDb4oHelper.commit() ;
		mDb4oHelper.close() ;
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mImageWorker.getImageCache().clearMemoryCache() ;
		if(mAsyncthread != null ) mAsyncthread.interrupt() ;
		if(mAutoPlay != null) mAutoPlay.interrupt() ;
		
		if(updater != null) updater.free(this) ;
		
	}
	
	//提前做好分享的数据准备
	protected void prepreForShare() {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(stream,
				Utils.IO_BUFFER_SIZE);
		getCurrentBitmap().compress(Bitmap.CompressFormat.JPEG, 90, bos);
		mCurrentImageBytes = stream.toByteArray();
		isImageByteInited = true;
	}

	//保存到sdcard
	protected void saveToSdcard() {
		File file = Utils.getSdcardFileDir(this);
		if (!file.exists()) {
			file.mkdir();
		}
		try {
			File imageFile = new File(file, System.currentTimeMillis()+".jpg");
			imageFile.createNewFile();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imageFile),Utils.IO_BUFFER_SIZE);
			getCurrentBitmap().compress(CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// SNS分享图片，使用异步初始化加载
	private void shareImage() {
		while (!isImageByteInited)	;
		MobclickAgent.onEvent(this, "share",mCategory) ;
		DataSendCallbackListener listener = new DataSendCallbackListener(){
            @Override
            public void onDataSendFailedWithException(
                    UMSNSException exception, UMSnsService.SHARE_TO userPlatform) {
            }
            @Override
            public void onDataSendFinished(RETURN_STATUS returnStatus, UMSnsService.SHARE_TO userPlatform) {
                switch (returnStatus)
                {
                case UPDATED:
                	MobclickAgent.onEvent(DetailActivity.this,"share_success",userPlatform.name());
                	((GirlsApplication)getApplication()).showToast("感谢您的分享.") ;
                    break;
                case REPEATED:
                	((GirlsApplication)getApplication()).showToast("重复的内容分享.") ;
                    break;
                default:
                    break;
                }
            }
        };
		UMSnsService.share(this, mCurrentImageBytes, new HashMap<String, String>(), listener);
	}

	private MyAsyncHandler getAsyncHandler() {
		if (mAsyncHandler == null) {
			mAsyncthread = new HandlerThread("async");
			mAsyncthread.start();
			mAsyncHandler = new MyAsyncHandler(mAsyncthread.getLooper(), this);
		}
		return mAsyncHandler;
	}

	private Bitmap getCurrentBitmap() {
		String temp = mExtImageWorkerAdapter.getItem(mPager.getCurrentItem())
				.toString();
		Logger.d("url", "url = " + temp);
		Bitmap bitmap = mImageWorker.getImageByUrl(temp);
		Logger.d("bitmap", "bitmap = " + bitmap);
		return bitmap;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public void onOptionsMenuClosed(android.view.Menu menu) {
		// 需要重新初始化相关变量，并且释放占用的byte[]
		isImageByteInited = false;
		mCurrentImageBytes = null;
		super.onOptionsMenuClosed(menu);
	}

	/**
	 * 由于将图片转换成byte[]，需要一定的时间,提前加载，使得操作流畅
	 * 
	 * @param menu
	 * @return
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		getAsyncHandler().sendEmptyMessage(MyAsyncHandler.WHAT_PREPARE_FOR_SHARE) ;
		
		//更新自动播放按钮
		if(mAutoPlay != null && mAutoPlay.isAutoPlay){
			menu.findItem(R.id.menu_auto_play).setTitle(R.string.menu_stop_play) ;
		}else{
			menu.findItem(R.id.menu_auto_play).setTitle(R.string.menu_play_automatic) ;
		}
		
		//更新收藏按钮
		final FolderItem item = mExtImageWorkerAdapter.getList().get(mPager.getCurrentItem() ) ;
		if(item.haveFaved || mDb4oHelper.getFavFolderItemByName(item.toString()) != null){
			menu.findItem(R.id.menu_fav).setTitle(R.string.menu_have_fav).setEnabled(false) ;
		}else{
			menu.findItem(R.id.menu_fav).setTitle(R.string.menu_fav) ;
		}
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Called by the ViewPager child fragments to load images via the one
	 * ImageWorker
	 * 
	 * @return
	 */
	public ImageWorker getImageWorker() {
		return mImageWorker;
	}

	/**
	 * The main adapter that backs the ViewPager. A subclass of
	 * FragmentStatePagerAdapter as there could be a large number of items in
	 * the ViewPager and we don't want to retain them all in memory at once but
	 * create/destroy them on the fly.
	 */
	private class ImagePagerAdapter extends FragmentStatePagerAdapter {
		private final int mSize;

		public ImagePagerAdapter(FragmentManager fm, int size) {
			super(fm);
			mSize = size;
		}

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public Fragment getItem(int position) {
			return DetailFragment.newInstance(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			final DetailFragment fragment = (DetailFragment) object;
			// As the item gets destroyed we try and cancel any existing work.
			fragment.cancelWork();
			super.destroyItem(container, position, object);
		}
		
	}

	/**
	 * Set on the ImageView in the ViewPager children fragments, to
	 * enable/disable low profile mode when the ImageView is touched.
	 */
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		final int vis = mPager.getSystemUiVisibility();
		if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
			mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
		} else {
			mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
		}
	}

	// 自动播放的辅助类
	class AutoPlay extends Thread {
		private MyMainHandler mMainHandler;
		boolean isAutoPlay;

		public AutoPlay(MyMainHandler handler) {
			super();
			this.mMainHandler = handler;
		}

		//开始或停止播放控制
		public void startOrStopPlay() {
			isAutoPlay = !isAutoPlay;
		}
		
		@Override
		public synchronized void start() {
			super.start();
		}

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(3000);
					if (isAutoPlay)
						mMainHandler
								.sendEmptyMessage(MyMainHandler.WHAT_AUTO_PLAY);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	static class MyAsyncHandler extends Handler {
		public static final int WHAT_SET_WALLPAPER = 0;
		public static final int WHAT_PREPARE_FOR_SHARE = 1;
		public static final int WHAT_SAVE_FILE = 2;
		public static final int WHAT_SAVE_FAV_ITEM = 3;
		public static final int WHAT_GET_YOUMI_POINT = 4;
		private WeakReference<DetailActivity> mActivity;

		public MyAsyncHandler(Looper looper, DetailActivity activity) {
			super(looper);
			mActivity = new WeakReference<DetailActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			DetailActivity theActivity = mActivity.get();
			if (theActivity == null)
				return;
			switch (msg.what) {
			case WHAT_SET_WALLPAPER:
				try {
					WallpaperManager.getInstance(theActivity).setBitmap(
							(Bitmap) msg.obj);
					theActivity.mMainHandler
							.sendEmptyMessage(MyMainHandler.WHAT_SET_WALLPAPER_SUCCESS);
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			case WHAT_PREPARE_FOR_SHARE:
				theActivity.prepreForShare() ;
				break;
			case WHAT_SAVE_FILE:
				theActivity.saveToSdcard();
				theActivity.mMainHandler
						.sendEmptyMessage(MyMainHandler.WHAT_SAVE_FILE_SUCCESS);
				break;
			case WHAT_SAVE_FAV_ITEM:
				theActivity.saveToFav() ;
				theActivity.mMainHandler
				.sendEmptyMessage(MyMainHandler.WHAT_SAVE_FAV_SUCCESS);
			case WHAT_GET_YOUMI_POINT:
//				theActivity.getUpdatePoints("积分", YoumiPointsManager.queryPoints(theActivity)) ;
				break ;
			}
		}
	}

	static class MyMainHandler extends Handler {
		public static final int WHAT_AUTO_PLAY = 0;
		public static final int WHAT_SET_WALLPAPER_SUCCESS = 1;
		public static final int WHAT_SAVE_FILE_SUCCESS = 2;
		public static final int WHAT_SAVE_FAV_SUCCESS = 3;
		public static final int WHAT_UPDATE_POINTS = 4;
		private WeakReference<DetailActivity> mActivity;

		MyMainHandler(DetailActivity activity) {
			mActivity = new WeakReference<DetailActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			DetailActivity theActivity = mActivity.get();
			if (theActivity == null)
				return;
			switch (msg.what) {
			case WHAT_AUTO_PLAY:
				int position = theActivity.mPager.getCurrentItem();
				if (position < theActivity.mAdapter.getCount() - 1) {
					position++;
					theActivity.mPager.setCurrentItem(position);
				} else {
					theActivity.mAutoPlay.isAutoPlay = false ;
					((GirlsApplication) theActivity.getApplication())
							.showToast("已经是最后一张了");
				}
				break;
			case WHAT_SET_WALLPAPER_SUCCESS:
				((GirlsApplication) theActivity.getApplication())
						.showToast("壁纸设置成功");
				break;
			case WHAT_SAVE_FILE_SUCCESS:
				((GirlsApplication) theActivity.getApplication())
						.showToast("图片已经保存到\""
								+ Utils.getSdcardFileDir(theActivity) + "\"文件夹下.");
				break;
				
			case WHAT_SAVE_FAV_SUCCESS:
				((GirlsApplication) theActivity.getApplication())
				.showToast("成功收藏到我的美女.");
				break ;
			case WHAT_UPDATE_POINTS:
				((GirlsApplication) theActivity.getApplication())
				.showToast(msg.obj.toString());
				break ;
			}
		}
	}
	
	public void getUpdatePoints(String currencyName, int pointTotal) {
		String msgText = null ;
		mCurrentPoint = pointTotal ;
		Logger.d("ImageDetailActivity", "----getUpdatePoints mCurrentPoint="+mCurrentPoint) ;
		if(pointTotal >= mUnlockTime*mUnlockBase) {
			Editor editor = getSharedPreferences(Config.SHAF_NAME, MODE_PRIVATE).edit() ;
			editor.putBoolean(Config.SHAF_UNLOCKED, true) ;
			editor.commit() ;
			isUnlocked = true ;
			MobclickAgent.onEvent(this, "unlock_success") ;
			if(mUnlockTime > 0) msgText = "解锁成功,感谢您的支持" ;
			if(updater != null) updater.spendPoints(this,pointTotal) ;
		}
		
		if(msgText != null){
			Message msg = mMainHandler.obtainMessage(MyMainHandler.WHAT_UPDATE_POINTS) ;
			msg.obj = msgText ;
			msg.sendToTarget() ;
		}
	}

	public void getUpdatePointsFailed(String error) {
		Message msg = mMainHandler.obtainMessage(MyMainHandler.WHAT_UPDATE_POINTS) ;
		msg.obj = "网络连接失败,请检查网络连接或重新打开应用" ;
		msg.sendToTarget() ;
	}
	
	void doPositiveClick(){
		if(!isUnlocked) updater.showOffers(this) ;
	}
	
	public GetPointSuccessCallBack successCallBack = new GetPointSuccessCallBack() {
		
		@Override
		public void getPointSuccess(String currenyName, float amount) {
			getUpdatePoints(currenyName, (int)amount) ;
		}
	}; 
	
	public GetPointFailureCallBack failureCallBack = new GetPointFailureCallBack() {
		
		@Override
		public void getPointFailure(String error) {
			getUpdatePointsFailed(error) ;
		}
	};
	
	public static class MyAlertDialogFragment extends SherlockDialogFragment {

        public static MyAlertDialogFragment newInstance(String title) {
            MyAlertDialogFragment frag = new MyAlertDialogFragment();
            Bundle args = new Bundle();
            args.putString("title", title);
            frag.setArguments(args);
            return frag;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            String title = getArguments().getString("title");

            return new AlertDialog.Builder(getActivity())
                    .setMessage(title)
                    .setPositiveButton(R.string.point_dialog_ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            	((DetailActivity)getSherlockActivity()).doPositiveClick() ;
                            }
                        }
                    )
                    .setNegativeButton(R.string.point_dialog_cancle,
                       null)
                    .create();
        }
        
    }
	
	TouchEventListener touchEventListener = new TouchEventListener() {
		
		@Override
		public void onZoomToOrigin() {
			Logger.d(TAG, "onZoomToOrigin") ;
			mPager.setEnabled(true) ;
		}
		
		@Override
		public void onZoom() {
			Logger.d(TAG, "onZoom") ;
			mPager.setEnabled(false) ;
		}
	} ;
	
	public static class EnableDisableViewPager  extends ViewPager{
		private boolean enabled = true ;
		
		public EnableDisableViewPager(Context context, AttributeSet attrs) {
			super(context,attrs);
		}
		
		@Override
		public boolean onInterceptTouchEvent(MotionEvent arg0) {
			// TODO Auto-generated method stub
			if(enabled) return super.onInterceptTouchEvent(arg0);
			else return false ;
		}

		public boolean isEnabled() {
			return enabled;
		}

		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}
	}
}
